package org.janon.httpproxy.client.method;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.Socket;
import java.util.Date;

import org.janon.httpproxy.ClientReadFromServer;
import org.janon.httpproxy.HttpModel;
import org.janon.httpproxy.HttpSession;
import org.janon.httpproxy.HttpUtil;
import org.janon.httpproxy.Log;
import org.janon.httpproxy.RequestLogStream;
import org.janon.httpproxy.client.ClientWrite;

public class ConnectMethod
{
	private final static int BUFFER_SIZE = 96000;
	
	public static ClientReadFromServer doMethod(HttpModel httpModel, BufferedInputStream server_in, BufferedOutputStream server_out, BufferedInputStream client_in, BufferedOutputStream client_out, HttpSession session, RequestLogStream rls, String serverHost, int serverPort, Socket serverSocket) throws Exception
	{
		boolean flag = false;
		ClientWrite.write(httpModel, server_out, rls);
		String temp;
		String serverConnectKey = null;
		while(true){
			temp = HttpUtil.readLine(server_in);
			if(HttpUtil.startsWith(temp, "Set-Cookies: "))
			{
				serverConnectKey = temp.substring(13);
				flag = true;
			}
			if (temp == null || temp.length() == 0)
			{
				break;
			}
		}
		
		if(flag)
		{
			client_out.write((httpModel.getHttpType() + " 200 Connection established" + HttpUtil.CRLF)
					.getBytes());
			Log.getInstance().writeRecordToFile(rls.getInputStream(), (httpModel.getHttpType() + " 200 Connection established"));
		}
		else
		{
			client_out.write((httpModel.getHttpType() + " 401 Denied" + HttpUtil.CRLF)
					.getBytes());
			client_out.write(("Connection: close" + HttpUtil.CRLF).getBytes());
			Log.getInstance().writeRecordToFile(rls.getInputStream(), (httpModel.getHttpType() + " 401 Denied"));
			Log.getInstance().writeRecordToFile(rls.getInputStream(), "Connection: close");
		}
		
		client_out.write(HttpUtil.CRLF.getBytes());
		client_out.flush();
		Log.getInstance().writeRecordToFile(rls.getInputStream(), "");
		
		try
		{
			ConnectReadMethod crm = new ConnectReadMethod(server_in,client_out,serverSocket);
			int bytes_read = 0;
			byte[] buf = new byte[BUFFER_SIZE];
			ConnectContinueThread cct = new ConnectContinueThread(serverHost, serverPort, serverConnectKey, httpModel,crm);
			cct.start();
			while ((bytes_read = client_in.read(buf)) != -1)
			{
				cct.setTime(new Date());
				SendConnectData.send(serverHost, serverPort, serverConnectKey, httpModel, buf, 0, bytes_read, crm);
				Log.getInstance().writeRecordToFile(rls.getOutputStream(), new String(buf, 0, bytes_read));
			}
			SendConnectData.send(serverHost, serverPort, serverConnectKey, httpModel, buf, 0, -1, crm);
			crm.removeServerInputStreams();
			cct.close();
		}
		catch (Exception e)
		{
		}
		return null;
	}
}
